<script src="../utils/request.js"></script>
<template>
  <div class="login">
    <div class="login-container">
      <!-- 左侧信息区 -->
      <div class="login-left">
        <div class="system-logo">
          <img src="@/assets/logo/logo.png" alt="系统Logo" class="logo-img" />
        </div>
        <h2 class="system-title">多氟多产业链供应系统</h2>
        <div class="system-description">
          <p>集成化 · 智能化 · 高效化</p>
          <div class="feature-list">
            <div class="feature-item">
              <i class="el-icon-coordinate"></i>
              <span>供应链一体化协同</span>
            </div>
            <div class="feature-item">
              <i class="el-icon-data-analysis"></i>
              <span>数据驱动决策支持</span>
            </div>
            <div class="feature-item">
              <i class="el-icon-s-operation"></i>
              <span>智能化供应管理</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-right">
        <div class="login-form-container">
          <h3 class="welcome-title">欢迎登录</h3>
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入账号"
                prefix-icon="el-icon-user"
              ></el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                prefix-icon="el-icon-lock"
                @keyup.enter.native="handleLogin"
              ></el-input>
            </el-form-item>

            <el-form-item prop="code" v-if="captchaEnabled">
              <el-input
                v-model="loginForm.code"
                placeholder="请输入验证码"
                style="width: 63%"
                prefix-icon="el-icon-key"
                @keyup.enter.native="handleLogin"
              ></el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img"/>
              </div>
            </el-form-item>

            <el-form-item class="remember-me-item">
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
              <a href="javascript:;" class="forget-password" @click="showForgetPasswordDialog">忘记密码?</a>
            </el-form-item>

            <el-form-item>
              <el-button
                :loading="loading"
                type="primary"
                class="login-button"
                @click.native.prevent="handleLogin"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登录中...</span>
              </el-button>
            </el-form-item>

            <div class="other-login-options" v-if="register">
              <div class="divider">
                <span class="divider-text">还没有账号?</span>
              </div>
              <router-link :to="'/register'" class="register-link">
                立即注册
              </router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 底部版权信息 -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>

    <!-- 忘记密码弹窗 -->
    <el-dialog
      title="重置密码"
      :visible.sync="forgetPasswordVisible"
      width="400px"
      center
      :close-on-click-modal="false">
      <el-form ref="resetPasswordForm" :model="resetPasswordForm" :rules="resetPasswordRules" label-width="0" class="reset-password-form">
        <el-form-item prop="username">
          <el-input
            v-model="resetPasswordForm.username"
            placeholder="请输入账号"
            prefix-icon="el-icon-user">
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="resetPasswordForm.email"
            placeholder="请输入邮箱"
            prefix-icon="el-icon-message">
            <el-button slot="append" @click="handleSendCode" :disabled="codeButtonDisabled">
              {{ codeButtonText }}
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="resetPasswordForm.code"
            placeholder="请输入验证码"
            prefix-icon="el-icon-key">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="resetPasswordForm.password"
            type="password"
            placeholder="请输入新密码"
            prefix-icon="el-icon-lock">
          </el-input>
          <div class="password-tips">密码须包含大小写字母、数字和特殊字符(@$!%*?&)，长度8-20位，且不能包含连续三个及以上的数字或字母</div>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            prefix-icon="el-icon-key">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleResetPassword" :loading="resetLoading">确 认</el-button>
        <el-button type="text" @click="returnToLogin" class="return-login">返回登录</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCodeImg, resetPassword } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import {getToken} from "@/utils/auth";
import request from '@/utils/request'

export default {
  name: "Login",
  data() {
    const validatePassword = (rule, value, callback) => {
      const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$/;
      if (!passwordPattern.test(value)) {
        callback(new Error("密码必须包含大小写字母、数字和特殊字符，长度8-20位"));
        return;
      }

      // 检查是否包含连续三个及以上的数字
      if (/\d{3,}/.test(value)) {
        callback(new Error("密码不能包含连续三个及以上的数字"));
        return;
      }

      // 检查是否包含连续三个及以上的小写字母
      if (/[a-z]{3,}/.test(value)) {
        callback(new Error("密码不能包含连续三个及以上的小写字母"));
        return;
      }

      // 检查是否包含连续三个及以上的大写字母
      if (/[A-Z]{3,}/.test(value)) {
        callback(new Error("密码不能包含连续三个及以上的大写字母"));
        return;
      }

      callback();
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.resetPasswordForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    const validateEmail = (rule, value, callback) => {
      const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!emailPattern.test(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    };

    return {
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      redirect: undefined,
      forgetPasswordVisible: false,
      resetPasswordForm: {
        username: "",
        email: "",
        code: "",
        password: "",
        confirmPassword: ""
      },
      resetPasswordRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]+$/, message: '账号只能包含字母和数字，不能包含特殊字符', trigger: 'blur' }
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入邮箱" },
          { validator: validateEmail, trigger: "blur" }
        ],
        code: [
          { required: true, trigger: "blur", message: "请输入验证码" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入新密码" },
          { min: 8, max: 20, message: "密码长度必须介于 8 和 20 之间", trigger: "blur" },
          { validator: validatePassword, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请确认新密码" },
          { validator: validateConfirmPassword, trigger: "blur" }
        ]
      },
      resetLoading: false,
      codeButtonDisabled: false,
      codeButtonText: "获取验证码",
      countdown: 60
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
      if (getToken()) {
        this.$store.dispatch('GetInfo').catch(() => {
          this.$store.dispatch('FedLogOut');
        });
      }
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove('rememberMe');
          }

          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$notify({
              title: '登录成功',
              message: '欢迎回来，正在跳转...',
              type: 'success',
              duration: 1500,
              position: 'top-right',
              customClass: 'login-notify'
            });
            this.$router.push({ path: this.redirect || "/official/index" }).catch(()=>{});
          }).catch((error) => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
            // 显示错误信息
            this.$notify({
              title: '登录失败',
              message: error.message || '用户名或密码错误',
              type: 'error',
              duration: 1500,
              position: 'top-right',
              customClass: 'login-notify'
            });
          });
        }
      });
    },
    showForgetPasswordDialog() {
      this.forgetPasswordVisible = true;
      this.$nextTick(() => {
        // 重置表单数据
        this.resetPasswordForm = {
          username: "",
          email: "",
          code: "",
          password: "",
          confirmPassword: ""
        };
        // 重置表单验证
        if (this.$refs.resetPasswordForm) {
          this.$refs.resetPasswordForm.resetFields();
        }
        // 重置验证码按钮状态
        this.codeButtonDisabled = false;
        this.codeButtonText = "获取验证码";
        this.countdown = 60;
      });
    },
    handleSendCode() {
      // 只验证邮箱字段
      this.$refs.resetPasswordForm.validateField('email', (errorMessage) => {
        if (errorMessage) {
          return;
        }

        this.codeButtonDisabled = true;
        this.countdown = 60;
        this.codeButtonText = `${this.countdown}秒后重试`;

        // 发送验证码请求
        request({
          url: '/system/user/sendEmail',
          method: 'post',
          params: {
            email: this.resetPasswordForm.email
          }
        }).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '发送成功',
              message: '验证码已发送到您的邮箱',
              type: 'success',
              duration: 1500,
              position: 'top-right',
              customClass: 'login-notify'
            });
            this.startCountdown();
          } else {
            this.$notify({
              title: '发送失败',
              message: res.msg || '验证码发送失败',
              type: 'error',
              duration: 1500,
              position: 'top-right',
              customClass: 'login-notify'
            });
            this.codeButtonDisabled = false;
            this.codeButtonText = '获取验证码';
          }
        }).catch(() => {
          this.$notify({
            title: '发送失败',
            message: '验证码发送失败',
            type: 'error',
            duration: 1500,
            position: 'top-right',
            customClass: 'login-notify'
          });
          this.codeButtonDisabled = false;
          this.codeButtonText = '获取验证码';
        });
      });
    },

    startCountdown() {
      const timer = setInterval(() => {
        this.countdown--;
        this.codeButtonText = `${this.countdown}秒后重试`;
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.codeButtonDisabled = false;
          this.codeButtonText = '获取验证码';
        }
      }, 1000);
    },

    handleResetPassword() {
      this.$refs.resetPasswordForm.validate(valid => {
        if (valid) {
          this.resetLoading = true;

          // 先验证验证码
          request({
            url: '/system/user/verifyCode',
            method: 'post',
            params: {
              email: this.resetPasswordForm.email,
              code: this.resetPasswordForm.code
            }
          }).then(res => {
            if (res.code === 200) {
              // 验证码正确，发送重置密码请求
              return request({
                url: '/auth/ResetPassword',
                method: 'post',
                data: {
                  userName: this.resetPasswordForm.username,
                  email: this.resetPasswordForm.email,
                  password: this.resetPasswordForm.password
                }
              });
            } else {
              throw new Error(res.msg || '验证码验证失败');
            }
          }).then(res => {
            if (res.code === 200) {
              this.$notify({
                title: '重置成功',
                message: '密码重置成功，请使用新密码登录',
                type: 'success',
                duration: 1500,
                position: 'top-right',
                customClass: 'login-notify'
              });
              this.forgetPasswordVisible = false;
              // 清空表单
              this.resetPasswordForm = {
                username: "",
                email: "",
                code: "",
                password: "",
                confirmPassword: ""
              };
              // 重置验证码按钮状态
              this.codeButtonDisabled = false;
              this.codeButtonText = "获取验证码";
              this.countdown = 60;
            } else {
              this.$notify({
                title: '重置失败',
                message: res.msg || '密码重置失败',
                type: 'error',
                duration: 1500,
                position: 'top-right',
                customClass: 'login-notify'
              });
            }
          }).catch(err => {
            this.$notify({
              title: '操作失败',
              message: err.message || '操作失败，请重试',
              type: 'error',
              duration: 1500,
              position: 'top-right',
              customClass: 'login-notify'
            });
          }).finally(() => {
            this.resetLoading = false;
          });
        }
      });
    },
    returnToLogin() {
      this.forgetPasswordVisible = false;
      this.resetPasswordForm = {
        username: "",
        email: "",
        code: "",
        password: "",
        confirmPassword: ""
      };
      // 重新获取验证码
      this.getCode();
    }
  }
};
</script>

<style lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("../assets/images/RegisterBG.jpg");
  background-size: cover;
  background-position: center;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
  }

  .login-container {
    display: flex;
    width: 900px;
    height: 550px;
    position: relative;
    z-index: 1;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);

    .login-left {
      width: 55%;
      background: linear-gradient(135deg, #1b6ec2, #0c4489);
      padding: 50px 40px;
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .system-logo {
        margin-bottom: 20px;

        .logo-img {
          height: 60px;
        }
      }

      .system-title {
        font-size: 28px;
        font-weight: 600;
        margin-bottom: 30px;
        letter-spacing: 1px;
      }

      .system-description {
        p {
          font-size: 18px;
          margin-bottom: 30px;
          opacity: 0.9;
        }

        .feature-list {
          margin-top: 40px;

          .feature-item {
            display: flex;
            align-items: center;
            margin-bottom: 20px;

            i {
              font-size: 24px;
              margin-right: 15px;
              background: rgba(255, 255, 255, 0.2);
              width: 40px;
              height: 40px;
              display: flex;
              align-items: center;
              justify-content: center;
              border-radius: 50%;
            }

            span {
              font-size: 16px;
              opacity: 0.9;
            }
          }
        }
      }
    }

    .login-right {
      width: 45%;
      background: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;

      .login-form-container {
        width: 80%;

        .welcome-title {
          font-size: 26px;
          font-weight: 600;
          color: #333;
          margin-bottom: 30px;
          text-align: center;
        }

        .login-form {
          .el-form-item {
            margin-bottom: 25px;

            .el-input__inner {
              height: 46px;
              line-height: 46px;
              padding-left: 40px;
              border-radius: 4px;
              font-size: 15px;
              border: 1px solid #e0e0e0;
              transition: all 0.3s;

              &:focus {
                border-color: #1b6ec2;
                box-shadow: 0 0 0 2px rgba(27, 110, 194, 0.2);
              }
            }

            .el-input__prefix {
              left: 12px;
              color: #909399;
            }
          }

          .remember-me-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;

            .el-checkbox {
              color: #606266;
            }

            .forget-password {
              color: #1b6ec2;
              font-size: 14px;
              text-decoration: none;

              &:hover {
                color: #3989e6;
                text-decoration: underline;
              }
            }
          }

          .login-button {
            width: 100%;
            height: 46px;
            font-size: 16px;
            font-weight: 500;
            background: #1b6ec2;
            border-color: #1b6ec2;
            transition: all 0.3s;

            &:hover {
              background: #3989e6;
              border-color: #3989e6;
              transform: translateY(-1px);
              box-shadow: 0 5px 15px rgba(27, 110, 194, 0.3);
            }

            &:active {
              transform: translateY(0);
            }
          }

          .other-login-options {
            margin-top: 25px;
            text-align: center;

            .divider {
              display: flex;
              align-items: center;
              margin: 15px 0;

              &:before, &:after {
                content: '';
                flex: 1;
                border-top: 1px solid #e0e0e0;
              }

              .divider-text {
                padding: 0 15px;
                font-size: 14px;
                color: #909399;
              }
            }

            .register-link {
              display: inline-block;
              width: 100%;
              height: 40px;
              line-height: 40px;
              border: 1px solid #1b6ec2;
              color: #1b6ec2;
              border-radius: 4px;
              text-decoration: none;
              font-size: 15px;
              transition: all 0.3s;

              &:hover {
                background: rgba(27, 110, 194, 0.1);
              }
            }
          }
        }
      }
    }
  }

  .login-code {
    position: absolute;
    right: 0;
    top: 0;
    height: 46px;
    width: 34%;

    img {
      height: 100%;
      width: 100%;
      cursor: pointer;
      border-radius: 0 4px 4px 0;
    }
  }

  .el-login-footer {
    position: absolute;
    bottom: 20px;
    width: 100%;
    text-align: center;
    color: rgba(255, 255, 255, 0.8);
    font-size: 13px;
    z-index: 1;
  }
}

/* 响应式设计 */
@media screen and (max-width: 992px) {
  .login {
    .login-container {
      width: 90%;
      height: auto;
    }
  }
}

/* 密码重置弹窗样式 */
.reset-password-form {
  .el-form-item {
    margin-bottom: 20px;
  }

  .el-input__inner {
    height: 40px;
    line-height: 40px;
    border-radius: 4px;
  }

  .el-input__prefix {
    left: 10px;
    color: #909399;
  }

  .password-tips {
    font-size: 12px;
    color: #909399;
    line-height: 1.2;
    padding-top: 4px;
  }

  .el-input-group__append {
    padding: 0 15px;
    background-color: #1b6ec2;
    border-color: #1b6ec2;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #3989e6;
      border-color: #3989e6;
    }

    &:disabled {
      background-color: #a0cfff;
      border-color: #a0cfff;
      cursor: not-allowed;
    }
  }
}

.dialog-footer {
  text-align: center;
  margin-top: 10px;

  .return-login {
    margin-left: 10px;
    font-size: 14px;
  }
}

@media screen and (max-width: 768px) {
  .login {
    .login-container {
      flex-direction: column;
      height: auto;
      max-height: 85vh;
      overflow-y: auto;

      .login-left {
        width: 100%;
        padding: 30px;

        .system-title {
          font-size: 24px;
          text-align: center;
        }

        .system-description {
          p {
            text-align: center;
          }

          .feature-list {
            display: none;
          }
        }
      }

      .login-right {
        width: 100%;
        padding: 30px 0;

        .login-form-container {
          width: 85%;
        }
      }
    }
  }
}

@media screen and (max-height: 700px) {
  .login {
    .login-container {
      height: auto;

      .login-left {
        padding: 20px;

        .system-logo {
          margin-bottom: 10px;

          .logo-img {
            height: 40px;
          }
        }

        .system-title {
          margin-bottom: 15px;
        }

        .system-description {
          p {
            margin-bottom: 15px;
          }
        }
      }
    }
  }
}

/* 登录通知样式 */
.login-notify {
  .el-notification__title {
    font-size: 16px;
    font-weight: bold;
  }
  .el-notification__content {
    font-size: 14px;
    margin: 8px 0;
  }
  &.el-notification--success {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
  }
  &.el-notification--error {
    background-color: #fef0f0;
    border-color: #fde2e2;
  }
}
</style>
